package cn.change360.newappchildrenenglish;

import android.app.Dialog;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.activeandroid.query.Select;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.change360.newappchildrenenglish.adapter.KeyboardAdapter;
import cn.change360.newappchildrenenglish.mode.Integrations;
import cn.change360.newappchildrenenglish.mode.Words;
import cn.change360.newappchildrenenglish.utils.FileUtil;
import cn.change360.newappchildrenenglish.utils.IntegraUtil;
import cn.change360.newappchildrenenglish.utils.MathematicsUtil;
import cn.change360.newappchildrenenglish.widget.WidgetDictation;

/*
* 听写本
* */

public class DictationActivity extends AppCompatActivity implements View.OnClickListener {

    ImageButton topbar_back;
    TextView topbar_title, integration;
    LinearLayout word_box;

    ImageView word_img;

    List<Words> wordsList;

    GridView gridview;

    //已经输入了几个字
    int input;

    //当前输入的单词
    String word;

    //没输入时的字符
    String noInput = "—";

    //总积分
    int intnumber;

    //键盘
    String[] wordArray = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "-4", "-3", "-2", "-1"};

    SoundPool soundPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dictation);

        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
        soundPool.load(this, R.raw.s_true, 1);
        soundPool.load(this, R.raw.s_false, 2);

        initView();
    }

    private void initView() {
        topbar_back = (ImageButton) findViewById(R.id.topbar_back);
        topbar_title = (TextView) findViewById(R.id.topbar_title);
        topbar_title.setText("听写本");
        topbar_back.setOnClickListener(this);

        word_box = (LinearLayout) findViewById(R.id.word_box);
        word_img = (ImageView) findViewById(R.id.word_img);

        gridview = (GridView) findViewById(R.id.gridview);
        integration = (TextView) findViewById(R.id.integration);

        wordsList = new Select().from(Words.class).where("word_column_id <?", 38).execute();

        intnumber = IntegraUtil.getIntegration();
        integration.setText(intnumber + "分");

        showData();

        gridview.setAdapter(new KeyboardAdapter(this, Arrays.asList(wordArray)));
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                WidgetDictation view1;
                if (i == wordArray.length - 1) {
                    submit();
                } else if (i == wordArray.length - 2) {
                    //倒数第二个，是退格
                    if (input > 0) {
                        view1 = (WidgetDictation) word_box.getChildAt(input - 1);
                        view1.setText(noInput);
                        input--;
                    } else if (input == 0) {
                        view1 = (WidgetDictation) word_box.getChildAt(input);
                        view1.setText(noInput);
                    }
                } else if (i == wordArray.length - 3) {
                    reading();
                } else if (i == wordArray.length - 4) {
                    showData();
                } else {
                    if (input == word.length()) {
                        Toast.makeText(DictationActivity.this, "检查完就提交吧~", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    view1 = (WidgetDictation) word_box.getChildAt(input);
                    view1.setText(wordArray[i]);
                    input++;
                }
            }
        });
    }

    private void showData() {
        input = 0;
        int re = MathematicsUtil.getRandom(0, wordsList.size() - 1);
        Words thisWord = wordsList.get(re);
        Bitmap bitmap = FileUtil.getImageFromAssetsFile(this, "word/" + thisWord.getWord_title() + ".jpg");
        if (bitmap == null) {
            showData();
        }
        word_img.setImageDrawable(new BitmapDrawable(bitmap));
        word = thisWord.getWord_title();
        word_box.removeAllViews();
        for (int i = 0; i < word.length(); i++) {
            WidgetDictation view = new WidgetDictation(this);
            view.setText(noInput);
            word_box.addView(view);
        }
    }

    private void reading() {
        AssetManager am = getAssets();
        AssetFileDescriptor afd;
        try {
            afd = am.openFd("raw/" + word + ".mp3");
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Dialog mAlertDialog;

    //提交检查
    private void submit() {
        if (input < word.length()) {
            WidgetDictation view1 = (WidgetDictation) word_box.getChildAt(input);
            Animation animationy = AnimationUtils.loadAnimation(this, R.anim.shake_y);
            view1.startAnimation(animationy);
            Toast.makeText(this, "还不完整", Toast.LENGTH_SHORT).show();
        } else {
            String inputWord = "";
            Boolean inok;
            for (int i = 0; i < word_box.getChildCount(); i++) {
                WidgetDictation view1 = (WidgetDictation) word_box.getChildAt(i);
                inputWord += view1.getText();
            }
            if (inputWord.toLowerCase().equals(word.toLowerCase())) {
                inok = true;
            } else {
                inok = false;
            }
            View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_show_score, null);
            TextView score_msg = (TextView) dialogView.findViewById(R.id.score_msg);
            ImageView img_star1 = (ImageView) dialogView.findViewById(R.id.img_star1);
            ImageView img_star2 = (ImageView) dialogView.findViewById(R.id.img_star2);
            ImageView img_star3 = (ImageView) dialogView.findViewById(R.id.img_star3);
            Animation starAnimation = AnimationUtils.loadAnimation(this, R.anim.zoom_in);
            if (inok) {
                img_star1.setVisibility(View.VISIBLE);
                img_star2.setVisibility(View.VISIBLE);
                img_star3.setVisibility(View.VISIBLE);
                score_msg.setText("你真聪明~！");
                showData();
                playSound(1);
                intnumber = plusIntegration(3, 101, "听写本中单词拼写正确");
                integration.setText(intnumber + "分");
                integration.startAnimation(starAnimation);
            } else {
                img_star1.setVisibility(View.GONE);
                img_star2.setVisibility(View.GONE);
                img_star3.setVisibility(View.GONE);
                score_msg.setText("不对哦~再想想~！");
                playSound(2);
                intnumber = plusIntegration(-1, 101, "听写本中单词拼写错误");
                integration.setText(intnumber + "分");
                integration.startAnimation(starAnimation);
            }
            img_star1.startAnimation(starAnimation);
            img_star2.startAnimation(starAnimation);
            img_star3.startAnimation(starAnimation);
            dialogView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mAlertDialog.cancel();
                }
            });
            mAlertDialog = new Dialog(this, R.style.theme_dialog);
            mAlertDialog.setContentView(dialogView);
            mAlertDialog.show();
        }
    }

    private void playSound(int m) {
        soundPool.play(m, 1, 1, 0, 0, 1);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.topbar_back:
                finish();
                break;
        }
    }

    public int plusIntegration(int integration_number, int integration_column_id, String integration_note) {
        Integrations integrations = new Integrations();
        integrations.setIntegration_number(integration_number);
        integrations.setIntegration_column_id(integration_column_id);
        integrations.setIntegration_note(integration_note);
        integrations.setIntegration_update_time(new Date().getTime());
        integrations.save();
        return IntegraUtil.getIntegration();
    }
}
